const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');
const auth = require('../middleware/auth');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置文件存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '..', 'uploads', 'notices');
    // 确保上传目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成文件名: 时间戳-原始文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024 // 限制文件大小为10MB
  }
});

// 获取通知列表 (管理员视角)
router.get('/', auth, async (req, res) => {
  try {
    // 验证用户权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足，只有管理员可以访问此接口' });
    }

    console.log('管理员通知列表路由被访问，参数:', req.query);
    const { page = 1, limit = 10, type = '' } = req.query;
    const offset = (page - 1) * limit;
    
    // 构建查询条件
    let query = `
      SELECT id, title, content, publishTime, publisherName as publisher, 
             isImportant as importance, targetRoles, attachments
      FROM notices
      WHERE 1=1
    `;
    
    const params = [];
    
    // 如果指定了类型，添加类型过滤
    if (type === 'important') {
      query += ` AND isImportant = 1`;
    } else if (type === 'normal') {
      query += ` AND isImportant = 0`;
    }
    
    // 获取总记录数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM notices
      WHERE 1=1
      ${type === 'important' ? ' AND isImportant = 1' : ''}
      ${type === 'normal' ? ' AND isImportant = 0' : ''}
    `;
    
    // 添加排序和分页
    query += ` ORDER BY publishTime DESC LIMIT ? OFFSET ?`;
    params.push(parseInt(limit), parseInt(offset));
    
    console.log('执行SQL查询:', query, params);
    
    const [rows] = await pool.query(query, params);
    const [countResult] = await pool.query(countQuery);
    const total = countResult[0].total;
    
    console.log('管理员通知查询结果:', rows);
    
    // 格式化数据
    const formattedRows = rows.map(notice => {
      // 从内容中提取纯文本作为简短描述
      const brief = notice.content
        .replace(/<[^>]+>/g, '') // 移除HTML标签
        .substring(0, 100) + (notice.content.length > 100 ? '...' : '');
      
      // 检查是否有附件
      const hasAttachment = notice.attachments && 
                           notice.attachments !== '[]' && 
                           notice.attachments !== null;
      
      // 解析目标角色
      let targetRoles = [];
      try {
        targetRoles = notice.targetRoles ? JSON.parse(notice.targetRoles) : [];
      } catch (e) {
        console.error('解析目标角色JSON失败:', e);
      }
      
      return {
        ...notice,
        brief,
        publishTime: new Date(notice.publishTime).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        }),
        hasAttachment: hasAttachment || false,
        important: notice.importance > 0,
        targetRoles: targetRoles
      };
    });
    
    res.json({
      notices: formattedRows,
      pagination: {
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取管理员通知列表失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取单个通知详情 (管理员视角)
router.get('/:id', auth, async (req, res) => {
  try {
    // 验证用户权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足，只有管理员可以访问此接口' });
    }
    
    const noticeId = req.params.id;
    console.log('管理员通知详情路由被访问，通知ID:', noticeId);
    
    // 查询通知详情
    const query = `
      SELECT id, title, content, publishTime, publisherName as publisher, 
             isImportant as importance, targetRoles, targetDepartments, 
             targetClasses, attachments
      FROM notices
      WHERE id = ?
    `;
    
    const [rows] = await pool.query(query, [noticeId]);
    
    if (rows.length === 0) {
      return res.status(404).json({ message: '通知不存在' });
    }
    
    const notice = rows[0];
    
    // 格式化日期
    notice.publishTime = new Date(notice.publishTime).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
    
    // 解析JSON字段
    try {
      notice.attachments = notice.attachments ? JSON.parse(notice.attachments) : [];
      notice.targetRoles = notice.targetRoles ? JSON.parse(notice.targetRoles) : [];
      notice.targetDepartments = notice.targetDepartments ? JSON.parse(notice.targetDepartments) : [];
      notice.targetClasses = notice.targetClasses ? JSON.parse(notice.targetClasses) : [];
    } catch (e) {
      console.error('解析JSON字段失败:', e);
      notice.attachments = [];
      notice.targetRoles = [];
      notice.targetDepartments = [];
      notice.targetClasses = [];
    }
    
    // 添加其他必要字段
    notice.important = notice.importance > 0;
    
    res.json(notice);
  } catch (error) {
    console.error('获取管理员通知详情失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 创建新通知
router.post('/', auth, async (req, res) => {
  try {
    // 验证用户权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足，只有管理员可以创建通知' });
    }
    
    const { title, content, isImportant, targetRoles, targetDepartments, targetClasses, attachments } = req.body;
    
    // 验证必填字段
    if (!title || !content) {
      return res.status(400).json({ message: '标题和内容不能为空' });
    }
    
    // 准备数据
    const publisherName = req.user.name || '管理员';
    // 移除 publisherId，使用 publisher 字段代替
    const publisher = req.user.id;
    const publishTime = new Date();
    
    // 将数组转换为JSON字符串
    const targetRolesJson = JSON.stringify(targetRoles || []);
    const targetDepartmentsJson = JSON.stringify(targetDepartments || []);
    const targetClassesJson = JSON.stringify(targetClasses || []);
    const attachmentsJson = JSON.stringify(attachments || []);
    
    // 修改插入语句，使用 publisher 而不是 publisherId
    const query = `
      INSERT INTO notices (
        title, content, publishTime, publisher, publisherName,
        isImportant, targetRoles, targetDepartments, targetClasses, attachments
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;
    
    const params = [
      title, content, publishTime, publisher, publisherName,
      isImportant ? 1 : 0, targetRolesJson, targetDepartmentsJson, targetClassesJson, attachmentsJson
    ];
    
    console.log('执行SQL:', query, params);
    
    const [result] = await pool.query(query, params);
    
    res.status(201).json({
      message: '通知创建成功',
      noticeId: result.insertId
    });
  } catch (error) {
    console.error('创建通知失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 更新通知
router.put('/:id', auth, async (req, res) => {
  try {
    // 验证用户权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足，只有管理员可以更新通知' });
    }
    
    const noticeId = req.params.id;
    const { title, content, isImportant, targetRoles, targetDepartments, targetClasses, attachments } = req.body;
    
    // 验证必填字段
    if (!title || !content) {
      return res.status(400).json({ message: '标题和内容不能为空' });
    }
    
    // 检查通知是否存在
    const [checkResult] = await pool.query('SELECT id FROM notices WHERE id = ?', [noticeId]);
    if (checkResult.length === 0) {
      return res.status(404).json({ message: '通知不存在' });
    }
    
    // 将数组转换为JSON字符串
    const targetRolesJson = JSON.stringify(targetRoles || []);
    const targetDepartmentsJson = JSON.stringify(targetDepartments || []);
    const targetClassesJson = JSON.stringify(targetClasses || []);
    const attachmentsJson = JSON.stringify(attachments || []);
    
    // 更新数据
    const query = `
      UPDATE notices SET
        title = ?,
        content = ?,
        isImportant = ?,
        targetRoles = ?,
        targetDepartments = ?,
        targetClasses = ?,
        attachments = ?,
        updateTime = NOW()
      WHERE id = ?
    `;
    
    const params = [
      title, content, isImportant ? 1 : 0,
      targetRolesJson, targetDepartmentsJson, targetClassesJson, attachmentsJson,
      noticeId
    ];
    
    await pool.query(query, params);
    
    res.json({
      message: '通知更新成功',
      noticeId: noticeId
    });
  } catch (error) {
    console.error('更新通知失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 删除通知
router.delete('/:id', auth, async (req, res) => {
  try {
    // 验证用户权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足，只有管理员可以删除通知' });
    }
    
    const noticeId = req.params.id;
    
    // 检查通知是否存在
    const [checkResult] = await pool.query('SELECT id, attachments FROM notices WHERE id = ?', [noticeId]);
    if (checkResult.length === 0) {
      return res.status(404).json({ message: '通知不存在' });
    }
    
    // 获取附件信息，以便删除文件
    let attachments = [];
    try {
      attachments = checkResult[0].attachments ? JSON.parse(checkResult[0].attachments) : [];
    } catch (e) {
      console.error('解析附件JSON失败:', e);
    }
    
    // 删除通知
    await pool.query('DELETE FROM notices WHERE id = ?', [noticeId]);
    
    // 删除附件文件（可选，取决于您的需求）
    // attachments.forEach(attachment => {
    //   const filePath = path.join(__dirname, '..', 'public', attachment.url);
    //   if (fs.existsSync(filePath)) {
    //     fs.unlinkSync(filePath);
    //   }
    // });
    
    res.json({
      message: '通知删除成功'
    });
  } catch (error) {
    console.error('删除通知失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 文件上传接口
router.post('/upload', auth, upload.single('file'), async (req, res) => {
  try {
    // 验证用户权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，只有管理员可以上传通知附件'
      });
    }

    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '未接收到文件'
      });
    }

    // 构建文件访问URL
    const fileUrl = `/uploads/notices/${req.file.filename}`;

    res.json({
      success: true,
      fileUrl: fileUrl,
      fileName: req.file.originalname,
      message: '文件上传成功'
    });

  } catch (error) {
    console.error('文件上传失败:', error);
    res.status(500).json({
      success: false,
      message: '文件上传失败',
      error: error.message
    });
  }
});

module.exports = router;